package com.itboye.ihomebank;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.itboye.ihomebank.adapter.HomeAdapter;
import com.itboye.ihomebank.base.BaseFragment;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.HouseBean;
import com.itboye.ihomebank.bean.HouseListBean;
import com.itboye.ihomebank.bean.LunBoBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.choosecity.CityListActivity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.controller.LoginController;
import com.itboye.ihomebank.custom.CarouselView;
import com.itboye.ihomebank.custom.MyListView;
import com.itboye.ihomebank.home.ActivityHomeSouSuo;
import com.itboye.ihomebank.home.ActivityHotSouSuo;
import com.itboye.ihomebank.homefragment.HouseDetailActivity;
import com.itboye.ihomebank.login.LoginActivity;
import com.itboye.ihomebank.me.ActivityFaBuHouse;
import com.itboye.ihomebank.myzhujia.ActivityHoseKeepingService;
import com.itboye.ihomebank.myzhujia.ActivityLivePayment;
import com.itboye.ihomebank.myzhujia.ActivityRepair;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.pullloadrefresh.PullToRefreshLayout;
import com.itboye.ihomebank.pullloadrefresh.PullToRefreshLayout.OnRefreshListener;
import com.itboye.ihomebank.pullloadrefresh.PullableScrollView;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.LoweImageView;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.XImageLoader;
import com.itboye.ihomebank.web.WebActivity;

/**
 * 首页
 * 
 */
public class HomeFragment extends BaseFragment implements OnClickListener,
		Observer, OnRefreshListener {
	private CarouselView banner_top;
	private PullableScrollView home_scrollView;
	private MyListView home_listview;
	PullToRefreshLayout refresh_view;
	private EditText edit_txt;
	private ArrayList<HouseBean> arrayListHouse = new ArrayList<HouseBean>();
	HousePresenter housePresenter;
	RelativeLayout home_city;// 切换城市
	RelativeLayout home_sousuo;// 搜索
	TextView tvcity;
	// 智能门锁，签约，预约，求租
	LinearLayout include_01, include_02, include_03, include_04;
	// 维修服务，一键缴费，家政服务，签证旅游
	RelativeLayout include_weixiu, include_jiaofei, include_jiazheng,
			include_qianzheng;

	private HomeAdapter adapter;
	protected String city;
	protected double lat;
	protected double lng;
	protected float radius;
	TextView textView2;
	private LocationClient locClient;
	protected boolean isFirstLoc = true;
	CarouselView lunbo;

	@Override
	public int initView() {

		return R.layout.fragment_home;
	}

	private void initLocation() {
		// TODO Auto-generated method stub
		// -----------location config ------------
		refresh_view.setOnRefreshListener(this);
		locClient = new LocationClient(getActivity());
		locClient.registerLocationListener(locListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll");// 设置坐标类型
		option.setAddrType("all");
		option.setScanSpan(1000);//
		locClient.setLocOption(option);
		locClient.start();
		// locationService = ((MyApplcation)
		// getActivity().getApplication()).locationService;
		// //
		// 获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
		// locationService.registerListener(myListener);
		// // 注册监听
		// locationService.setLocationOption(locationService
		// .getDefaultLocationClientOption());
		// locationService.start();// 定位SDK
	}

	/**
	 * 定位监听器
	 */
	BDLocationListener locListener = new BDLocationListener() {

		@Override
		public void onReceivePoi(BDLocation location) {

		}

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null) {
				return;
			}
			// 构造定位数据
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())//
					.direction(100)// 方向
					.latitude(location.getLatitude())//
					.longitude(location.getLongitude())//
					.build();
			// 设置定位数据
			lat = location.getLatitude();
			lng = location.getLongitude();
			// 第一次定位的时候，那地图中心店显示为定位到的位置
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				// MapStatusUpdate描述地图将要发生的变化
				// MapStatusUpdateFactory生成地图将要反生的变化
				MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(ll);
				// bdMap.setMyLocationEnabled(false);
				Toast.makeText(getActivity(), location.getAddrStr(),
						Toast.LENGTH_SHORT).show();
				if (null != location
						&& location.getLocType() != BDLocation.TypeServerError) {
					lat = location.getLatitude();
					lng = location.getLongitude();
					radius = location.getRadius();
					city = location.getCity();
					SPUtils.put(getActivity(), null, SPContants.SELECT_CITY,
							city==null?"杭州市":city);
//					SPUtils.put(getActivity(), null, SPContants.SELECT_AREA,
//							location.getDistrict());

					tvcity.setText(location.getCity() + location.getDistrict());
				}
			}
		}
	};
	private String uid;
	private UserPresenter userPresenter;

	@Override
	public void onMyActivityCreated() {
		userPresenter = new UserPresenter(this);
		userPresenter.lunbo("6045");
		uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
		housePresenter = new HousePresenter(this);
		housePresenter.queryHouse("330100", "", "", "", "", "", "", "", "", "",
				"", "", "", "100", "", uid);
		home_listview = (MyListView) getView().findViewById(R.id.mylistview);

		home_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						HouseDetailActivity.class);
				intent.putExtra("lng", lng);
				intent.putExtra("lat", lat);
				intent.putExtra("radius", radius);
				intent.putExtra("house_no",
						houseListBean.getData().get(position).getHouseNo());
				startActivity(intent);
			}
		});

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	private void getListViewData() {

		String c = (String) SPUtils.get(getActivity(), null,
				SPContants.SELECT_CITY, "");
		if (c == "") {
			tvcity.setText("定位中..");
		} else {
			tvcity.setText(c);
		}
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		initLocation();
	}

	public void onClick(View arg0) {
		Intent intent = null;
		switch (arg0.getId()) {
		case R.id.home_city:// 切换城市
			intent = new Intent(MyApplcation.ctx, CityListActivity.class);
			startActivity(intent);
			break;
		case R.id.home_sousuo:// 搜索
			intent = new Intent(MyApplcation.ctx, ActivityHotSouSuo.class);
			startActivity(intent);
			break;
		case R.id.include_01:// 发布
			uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
			if (uid.equals("")) {
				intent = new Intent(getActivity(), LoginActivity.class);
				startActivity(intent);
			} else {
				if (SPUtils.get(getActivity(), null,
						SPContants.IdentityValidate, "").equals("0")) {
					ByAlert.alert("请先实名制");
				} else if (SPUtils.get(getActivity(), null,
						SPContants.IdentityValidate, "").equals("2")) {
					ByAlert.alert("实名制审核中");
				} else {
					intent = new Intent(MyApplcation.ctx,
							ActivityFaBuHouse.class);
					startActivity(intent);
				}
			}
			break;
		case R.id.include_02:// 我的预约
			uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
			if (uid.equals("")) {
				intent = new Intent(getActivity(), LoginActivity.class);

				startActivity(intent);
			} else {
				intent = new Intent(getActivity(), ActivityHomeSouSuo.class);

				startActivity(intent);
			}
			// LoginController.onMyAppointmentClick(getActivity(), null);
			break;
		case R.id.include_03:// 我的签约
			LoginController.onMySignClick(getActivity(), null);
			break;
		case R.id.include_04:// 收藏
			LoginController.onMyCollectionClick(getActivity(), null);
			// intent = new Intent(getActivity(), ActivityShaiXuan.class);
//			uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
//			if (uid.equals("")) {
//				intent = new Intent(getActivity(), LoginActivity.class);
//
//				startActivity(intent);
//			} else {
//				intent = new Intent(getActivity(), WebActivity.class);
//				intent.putExtra("url", NetPublicConstant.WEB_URL
//						+ "/vip");
//				startActivity(intent);
//			}
			break;
		case R.id.include_weixiu:// 住家维修
			uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
			if (uid.equals("")) {
				intent = new Intent(getActivity(), LoginActivity.class);
				startActivity(intent);
			} else {
				intent = new Intent(getActivity(), ActivityRepair.class);
				startActivity(intent);
			}
			break;
		case R.id.include_jiaofei:// 一键缴费
			intent = new Intent(getActivity(), ActivityLivePayment.class);
			startActivity(intent);
			break;
		case R.id.include_jiazheng:// 家政服务
			intent = new Intent(getActivity(), ActivityHoseKeepingService.class);
			startActivity(intent);

			break;
		case R.id.include_qianzheng:// 签约旅行
			intent = new Intent(getActivity(), WebActivity.class);
			intent.putExtra("url", "http://hzzhongrui.travel.bbcmart.com/");
			intent.putExtra("title", "住家旅行");
			startActivity(intent);
			break;
		case R.id.textView2:
			//测试
//			StringRequest request = new StringRequest(
//					"http://api.ihomebank.com/public/index.php",
//					new Listener<String>() {
//
//						@Override
//						public void onResponse(String arg0) {
//							// TODO Auto-generated method stub
//							System.out.println("<><>" + arg0);
//						}
//					}, new ErrorListener() {
//
//						@Override
//						public void onErrorResponse(VolleyError arg0) {
//							// TODO Auto-generated method stub
//
//							System.out.println("<><>0"
//									+ arg0.getLocalizedMessage());
//						}
//					});
//			MyApplcation.addRequest(request);
			break;
		default:
			break;
		}
	}

	private HouseListBean houseListBean;
	private RelativeLayout one;

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.queryHouse_success) {
				houseListBean = (HouseListBean) entity.getData();
				if (houseListBean == null) {
					// no_data.setVisibility(View.VISIBLE);
					// sousuo_listview.setVisibility(View.GONE);
					return;
				}
				if (houseListBean.getData().size() <= 0) {
					// no_data.setVisibility(View.VISIBLE);
					// sousuo_listview.setVisibility(View.GONE);
					return;
				}
				// no_data.setVisibility(View.GONE);
				// sousuo_listview.setVisibility(View.VISIBLE);
				adapter = new HomeAdapter(getActivity(),
						houseListBean.getData());
				home_listview.setAdapter(adapter);
			} else if (entity.getEventType() == UserPresenter.lunbo_success) {
				List<LunBoBean> LunboBean = (List<LunBoBean>) entity.getData();
				ArrayList<ImageView> arrayBmps = new ArrayList<>();
				for (int i = 0; i < LunboBean.size(); i++) {
					LoweImageView imageView = new LoweImageView(getActivity());
					imageView.setScaleType(ScaleType.FIT_XY);
					XImageLoader.load(NetPublicConstant.IMAGE_URL
							+ LunboBean.get(i).getImg(), imageView);
					arrayBmps.add(imageView);
					imageView.setTag(i);
				}
				lunbo.setImageBitmaps(arrayBmps);
			} else if (entity.getEventType() == UserPresenter.lunbo_fail) {
				ByAlert.alert(entity.getData());
			}
			 one.setFocusable(true);
			 one.setFocusableInTouchMode(true);
			 one.requestFocus();
			// home_scrollView.smoothScrollTo(0, 0);

		}
		stopLoad();
	}

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		// TODO Auto-generated method stub
		this.refresh_view = pullToRefreshLayout;
		housePresenter.queryHouse("330100", "", "", "", "", "", "", "", "", "",
				"", "", "", "10000", "", uid);
	}

	@Override
	public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
		// TODO Auto-generated method stub

		this.refresh_view = pullToRefreshLayout;
		uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
		housePresenter.queryHouse("330100", "", "", "", "", "", "", "", "", "",
				"", "", "", "10000", "", uid);
	}

	public void stopLoad() {
		try {

			refresh_view.refreshFinish(PullToRefreshLayout.SUCCEED);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {

			refresh_view.loadmoreFinish(PullToRefreshLayout.SUCCEED);
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
}
